package com.szh.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.szh.common.dto.es.SkuEsModel;
import com.szh.gulimall.search.config.ElasticSearchConfig;
import com.szh.gulimall.search.constant.ElasticSearchConstant;
import com.szh.gulimall.search.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: SongZiHao
 * @date: 2022/12/18
 */
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProductSaveServiceImpl.class);

    @Autowired
    private RestHighLevelClient client;

    /**
     * 商品上架，也即将数据保存到ES中
     */
    @Override
    public boolean productUp(List<SkuEsModel> skuEsModels) throws IOException {
        //1.在ES中建立索引，product索引，建立映射关系，这一步在Kibana中完成了
        //对应的是resources目录下的gulimall_product_mapping.json
        //2.给ES中保存这些数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(ElasticSearchConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        //如果批量错误
        boolean hasFailures = bulkResponse.hasFailures();
        //将上架成功的商品id组装成List，打印日志
        BulkItemResponse[] items = bulkResponse.getItems();
        List<String> productIds = Arrays.stream(items)
                .map(BulkItemResponse::getId).collect(Collectors.toList());
        LOGGER.info("商品上架完成：{}，返回数据：{}", productIds, bulkResponse.toString());
        return hasFailures;
    }
}
